package com.wsy.util;

import lombok.SneakyThrows;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

public class FileUtil {
    /**
     * 图片上传
     *
     * @param uploadFile
     * @param path
     * @return 返回图片保存的路径
     */
    //lombok抛出异常
    @SneakyThrows
    public static String upload(MultipartFile uploadFile, String path){
        if(uploadFile.isEmpty()){
            return "请选择上传文件";
        }
        String realPath = "src/main/resources/"+path;
        File file = new File(realPath);
        //如果文件夹不存在则创建
        if (!file.isDirectory()){
            file.mkdirs();
        }
        //获取原始的名字
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        //构建真实的文件路径
        File newFile = new File(file.getAbsolutePath()+"/" + newName);
        //转存文件到指定路径，如果文件名重复的话，将会覆盖掉之前的文件,这里是把文件上传到 “绝对路径”
        uploadFile.transferTo(newFile);
        return realPath+newName;
    }
    @SneakyThrows
    public static String uploadFront(MultipartFile uploadFile){
        if(uploadFile.isEmpty()){
            return "请选择上传文件";
        }
        String realPath = "D:\\课程\\S3\\shopping\\src\\assets\\book\\";
        File file = new File(realPath);
        //如果文件夹不存在则创建
        if (!file.isDirectory()){
            file.mkdirs();
        }
        //获取原始的名字
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        //构建真实的文件路径
        File newFile = new File(file.getAbsolutePath()+"/" + newName);
        //转存文件到指定路径，如果文件名重复的话，将会覆盖掉之前的文件,这里是把文件上传到 “绝对路径”
        uploadFile.transferTo(newFile);
        return realPath+newName;
    }

    /**
     * 文件删除
     * @param path 文件路径
     * @return
     */
    @SneakyThrows
    public static boolean remove( String path){
        File file = new File(path);
        return file.delete();
    }
}
